package com.cmj.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cmj.Utils.BeanCopyUtils;
import com.cmj.Utils.SecurityUtils;
import com.cmj.Utils.SystemConverter;
import com.cmj.dao.MenuMapper;
import com.cmj.domain.ResponseResult;
import com.cmj.domain.SystemConstants;
import com.cmj.domain.dto.MenuDto;
import com.cmj.domain.entity.Menu;
import com.cmj.domain.vo.MenuTreeVo;
import com.cmj.domain.vo.MenuVo;
import com.cmj.domain.vo.RoleMenuTreeSelectVo;
import com.cmj.service.MenuService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service("menuService")
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Resource
    private MenuMapper menuMapper;

    @Override
    public List<String> selectPermsByUserId(Long id) {
        //如果是管理员，返回所有的权限
        if(id == 1L){
            LambdaQueryWrapper<Menu> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(Menu::getMenuType, SystemConstants.MENU,SystemConstants.BUTTON);
            wrapper.eq(Menu::getStatus,SystemConstants.STATUS_NORMAL);
            List<Menu> menus = list(wrapper);
            List<String> perms = menus.stream()
                    .map(Menu::getPerms)
                    .collect(Collectors.toList());
            return perms;
        }
        //否则返回所具有的权限
        return getBaseMapper().selectPermsByUserId(id);
    }

    @Override
    public List<Menu> selectRouterMenuTreeByUserId(Long userId) {
        MenuMapper menuMapper = getBaseMapper();
        List<Menu> menus = null;
        //判断是否是管理员
        if(SecurityUtils.isAdmin()){
            //如果是 获取所有符合要求的Menu
            menus = menuMapper.selectAllRouterMenu();
        }else{
            //否则  获取当前用户所具有的Menu
            menus = menuMapper.selectRouterMenuTreeByUserId(userId);
        }

        //构建tree
        //先找出第一层的菜单  然后去找他们的子菜单设置到children属性中
        List<Menu> menuTree = builderMenuTree(menus,0L);
        return menuTree;
    }

    @Override
    public ResponseResult getMenuList(MenuDto menuDto) {
        LambdaQueryWrapper<Menu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasText(menuDto.getMenuName()),Menu::getMenuName,menuDto.getMenuName());
        wrapper.eq(StringUtils.hasText(menuDto.getStatus()),Menu::getStatus,menuDto.getStatus());

        List<Menu> menus = menuMapper.selectList(wrapper);
        return ResponseResult.okResult(menus);
    }

    @Override
    public ResponseResult<Menu> addMenu(Menu menu) {
        int insert = menuMapper.insert(menu);
        if (insert == 0){
            new RuntimeException(SystemConstants.INSERT_FAIL);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult delMenu(Integer[] ids) {
        int i = menuMapper.deleteBatchIds(Arrays.asList(ids));
        if (i == 0){
            new RuntimeException(SystemConstants.DELETE_FAIL);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getMenu(Long id) {
        Menu menu = menuMapper.selectById(id);
        MenuVo menuVo = BeanCopyUtils.copyBean(menu, MenuVo.class);
        return ResponseResult.okResult(menuVo);
    }

    @Override
    public ResponseResult updateMenu(Menu menu) {
        int i = menuMapper.updateById(menu);
        if (i == 0){
            new RuntimeException(SystemConstants.UPDATE_FAIL);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getUserMenuTree(Long id) {
        List<Menu> menus = (List<Menu>) getMenuList(new MenuDto()).getData();
        List<Long> checkId = menuMapper.getMenuListByRoleId(id);
        List<MenuTreeVo> menuTreeVos = SystemConverter.builderMenuTreeVo(menus);
        RoleMenuTreeSelectVo vo = new RoleMenuTreeSelectVo(checkId,menuTreeVos);
        return ResponseResult.okResult(vo);
    }


    private List<Menu> builderMenuTree(List<Menu> menus, Long parentId) {
        List<Menu> menuTree = menus.stream()
                .filter(menu -> menu.getParentId().equals(parentId))
                .map(menu -> menu.setChildren(getChildren(menu, menus)))
                .collect(Collectors.toList());
        return menuTree;
    }

    /**
     * 获取存入参数的 子Menu集合
     * @param menu
     * @param menus
     * @return
     */
    private List<Menu> getChildren(Menu menu, List<Menu> menus) {
        List<Menu> childrenList = menus.stream()
                .filter(m -> m.getParentId().equals(menu.getId()))
                .map(m->m.setChildren(getChildren(m,menus)))
                .collect(Collectors.toList());
        return childrenList;
    }
}